#include "hsv_handle.h"

void RGB2HSV(u8 r, u8 g, u8 b, float *h, float *s, float *v) {
    float max = r > g? (r > b? r : b) : (g > b? g : b);
    float min = r < g? (r < b? r : b) : (g < b? g : b);

    // 计算 hue
    if (min == max) {
        *h = 0;
    } else if (max == r && g >= b) {
        *h = 60 * (g - b) / (max - min);
    } else if (max == r && g < b) {
        *h = 360 + 60 * (g - b) / (max - min);
    } else if (max == g) {
        *h = 120 + 60 * (b - r) / (max - min);
    } else {
        *h = 240 + 60 * (r - g) / (max - min);
    }

    // 计算 saturation
    if (max == 0) {
        *s = 0;
    } else {
        *s = (max - min) / max;
    }

    // 计算 v / brightness
    *v = max / 255.0;
}

void HSV2RGB(float h, float s, float v, unsigned char *r, unsigned char *g, unsigned char *b) {
    // s,v为小数表示，如0.25表示25
    int hi = (int)(floor(h / 60)) % 6;
    float f = h / 60 - hi;
    float p = v * (1 - s);
    float q = v * (1 - f * s);
    float t = v * (1 - (1 - f) * s);
    float r0 = 0, g0 = 0, b0 = 0;
    switch (hi) {
        case 0:
            r0 = v;
            g0 = t;
            b0 = p;
            break;
        case 1:
            r0 = q;
            g0 = v;
            b0 = p;
            break;
        case 2:
            r0 = p;
            g0 = v;
            b0 = t;
            break;
        case 3:
            r0 = p;
            g0 = q;
            b0 = v;
            break;
        case 4:
            r0 = t;
            g0 = p;
            b0 = v;
            break;
        case 5:
            r0 = v;
            g0 = p;
            b0 = q;
            break;
    }

    // 四舍五入取整
    *r = (unsigned char)round(r0 * 255);
    *g = (unsigned char)round(g0 * 255);
    *b = (unsigned char)round(b0 * 255);
}


void AdjustBrightness(float brightnessFactor, u8 *r, u8 *g, u8 *b) 
{
    float h, s, v;
    RGB2HSV(*r, *g, *b, &h, &s, &v);
    // Adjust the Value (brightness) component
    v *= brightnessFactor;
    v = fmax(0, fmin(v, 1)); // Ensure value is within valid range
    // Convert back to RGB
    //饱和度
    //s *= 1.2;
    HSV2RGB(h, s, v, r, g, b);
}